import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user.js'
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      component: () => import('@/views/home/layout.vue'),
      children: [
        {
          path: '/',
          redirect: '/home'
        },
        {
          path: '/home',
          name: 'home',
          component: () => import('@/views/home/home/home.vue')
        },
        {
          path: '/category/:id?',
          name: 'category',
          component: () => import('@/views/home/home/category.vue')
        },
        {
          path: '/cart',
          name: 'cart',
          component: () => import('@/views/home/home/cart.vue')
        },
        {
          path: '/allCategory/:id?',
          name: 'allCategory',
          component: () => import('@/views/home/home/allCategory.vue')
        },
        {
          path: '/production/:id?',
          name: 'production',
          component: () => import('@/views/home/home/production.vue')
        },
        {
          path: '/pay',
          name: 'pay',
          component: () => import('@/views/home/home/pay.vue')
        }
      ]
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/login/login.vue')
    }
  ]
})

const tokenRoute = ['/production', '/cart', '/pay']
router.beforeEach((to) => {
  const user = useUserStore()
  if (tokenRoute.includes(to.path) && !user.userInfo.token) {
    return { name: 'login' }
  }
  if (user.userInfo.token && to.path === '/login') return { name: 'home' }
  return true
})
export default router
